package com.lewis.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lewis.jpa.entity.Location;
import com.lewis.service.MetaTypeService;

@Controller
public class LocationController {

	private static final Logger LOGGER = Logger.getLogger(LocationController.class);
	
	@Autowired
	private MetaTypeService metaTypeService;
	
	@RequestMapping(value = "/addLocation", method = RequestMethod.GET)
	public void addLocation(HttpServletRequest request, HttpServletResponse response){
		
		LOGGER.info("addLocation entered");
		
		String city = request.getParameter("city");
		String country = request.getParameter("country");
		
		Location location = new Location();
		location.setCity(city);
		location.setCountry(country);
		
		List<Location> list = new ArrayList<Location>();
		list.add(location);
		
		metaTypeService.createLocations(list);
		
		response.setContentType("text/html");
        PrintWriter writer;
		try {
			writer = response.getWriter();
	        writer.println("<html>");
	        writer.println("<head>");
	        writer.println("<title>add a location</title>");
	        writer.println("</head>");
	        writer.println("<body bgcolor=white>");
	        writer.println("new location created. Country: " + country + "  city : " + city);
	        writer.println("have a nice day");

	        writer.println("</body>");
	        writer.println("</html>");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@RequestMapping(value = "/getLocationsFromCache", method = RequestMethod.GET)
	public void getLocationsFromCache(HttpServletRequest request, HttpServletResponse response){
		CacheManager cacheManager = CacheManager.getInstance();
		Cache cache = cacheManager.getCache("com.lewis.jpa.entity.Location");
		for (Object str: cache.getKeys()){
			System.out.println("key is " + str + "   the value is " + cache.get(str));
		}
		
	}
	
}
